var myApp = sy.getModule('myApp',[]);
myApp.directive('onFinishRenderFilters', function ($timeout) {
    return {
        restrict: 'A',
        link: function(scope, element, attr) {
            if (scope.$last === true) {
                $timeout(function() {
                    scope.$emit('ngRepeatFinished',attr.onFinishRenderFilters);
                });
            }
        }
    };
});
myApp.controller('CateController', function($scope,$http) {
  $scope.cates = [];
  $scope.cateCode = '';
  $scope.storeList = [];
  $scope.busy = false;
  $scope.page = 1;
  $scope.limit = 10;
  $scope.hasMore = true;
  sy.openLoad();
  var nowselect = sy.getUrlParam("select");
  if(nowselect) $scope.cateCode = nowselect;
  $scope.cb = function(){
	  $scope.busy = false;
	  $scope.nextPage();
  }
  
  if(sessionStorage.geoLat == undefined){
	  getCurrentPosition($scope.cb);
  }else{
	  $scope.busy = false;
  }
  
  $http.post("/m/i/cateList",{location:2})
		.success(function (data) {
			$scope.cates = data;
			if($scope.cateCode){
				$scope.store($scope.cateCode);
			}else if (data){
				$scope.cateCode = data[0].code;
				$scope.store(data[0].code);
			}
            sy.closeLoad();
        }).error(function(data, status) {
        	sy.closeLoad();
		});
  
  $scope.nextPage = function() {
	  if ($scope.busy || !$scope.hasMore || sy.areaCode == undefined) return;
	  $scope.busy = true;
      sy.openLoad();
      $http.post("/m/store/list",{
    	  		areaCode:sy.areaCode,
    	  		page:$scope.page,limit:$scope.limit,
    	  		catecode:$scope.cateCode,
    	  		keyword:$scope.keyword,
    	  		lat : sessionStorage.geoLat,
				lng : sessionStorage.geoLng
      		})
			.success(function (data) {
				if(data.length < $scope.limit)$scope.hasMore = false;
				$.each(data,function(i,o){
					$scope.storeList.push(o);
				});
				$scope.busy = false;
				$scope.page += 1;
	            sy.closeLoad();
	        }).error(function(data, status) {
	        	sy.closeLoad();
			});
  };
  
  $scope.store = function(cate){
	  $scope.cateCode = cate;
	  $scope.busy = false;
	  $scope.page = 1;
	  $scope.limit = 10;
	  $scope.hasMore = true;
	  $scope.storeList = [];
	  $scope.nextPage();
  };
  
  $scope.$on('ngRepeatFinished', function (event,data) {
		if(data == 'cate'){
			var initNavSlider = function(sliderContainerId){
				var navSwiper = new Swiper('#' + sliderContainerId,{
					pagination: '',
					createPagination: false,
					paginationClickable: false,
					slidesPerView: 'auto'
				})
			}
		
			initNavSlider('navSlider');//初始化分类导航触屏滑动
		}
	});
  
  $scope.storeDetail = function(id){
	location.href = '/m/s/'+id;  
  };
  
});
